import {CameraControls, Environment, Gltf, Lightformer} from '@react-three/drei'
import {CuboidCollider, Physics, RigidBody} from '@react-three/rapier'
import {useEffect, useState} from 'react'
import {Joystick, onPlayerJoin} from 'playroomkit'
import {GameArea} from './GameArea.jsx'
import {CarController} from './CarController.jsx'
import {CustomGameLight} from './CustomGameLight.jsx'

export const Game = (props) => {

  const [players, setPlayers] = useState([])

  useEffect(() => {
    onPlayerJoin((state) => {
      const controls = new Joystick(state, {
        type: 'angular',
        // 当翻车时，重新生成车辆
        buttons: [{id: 'Respawn', label: '重置'}]
      })
      const newPlayer = {state, controls}
      setPlayers((players) => [...players, newPlayer])
      state.onQuit(() => {
        setPlayers((players) => players.filter((p) => p.state.id !== state.id))
      })
    })
  }, [])

  return (
    <>
      <group>
        {/* <CameraControls/> */}
        <CustomGameLight />
        <Physics >
          {players.map(({state, controls}) => (
            <CarController key={state.id} state={state} controls={controls}/>
          ))}
          {/* type="trimesh" 精确碰撞 */}
          <RigidBody type="fixed" colliders="hull" rotation-y={Math.PI}>
            <GameArea/>
          </RigidBody>
          <RigidBody
            type="fixed"
            sensor
            colliders={false}
            position-y={-5}
            name="void"
          >
            <CuboidCollider args={[20, 3, 20]}/>
          </RigidBody>
          <Gltf src="/models/map_road.glb"/>
        </Physics>
      </group>
    </>
  )
}
